#import "DetailViewController+Print.h"
#import "RNConstants.h"
#import "RNCategory.h"
#import "RNAisle.h"
#import "RNList.h"
#import "RNListItem.h"
#import "RNItem.h"
#import "RNDetailHeader.h"
#import "RNDetailPrintView.h"

static CGFloat const genericHeight = 17.0f;
static CGFloat const listContainerHeight = 38.0f;
static CGFloat const itemWithNotesHeight = 33.0f;

@implementation DetailViewController (DetailViewControllerPrintMethods)

-(IBAction)printDetailViewAction:(id)sender {
    RNDetailPrintView *detailPrintView = [[RNDetailPrintView alloc] initWithFrame:NSZeroRect];
    [detailPrintView setDetailTreeController:[self detailTreeController]];
    [detailPrintView setRootObject:[self rootObject]];
    NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:detailPrintView];
    [printOperation runOperation];
}

-(NSView *)printView {
    if (!printView_) {
        [NSBundle loadNibNamed:@"PrintView" owner:self];
    }
    return printView_;
}

-(NSCell *)printCellForItem:(id)item {
    id representedObject = [item representedObject]; // Using bindings to NSTreeController, item is an NSTreeNode
    NSString *key = RNEmptyCellKey;
    if ([representedObject isKindOfClass:[RNCategory class]])
        key = [RNCategory showsChildren] ? RNPrintListContainerCellKey : RNPrintContainerCellKey;
    else if ([representedObject isKindOfClass:[RNAisle class]])
        key = [RNAisle showsChildren] ? RNPrintListContainerCellKey : RNPrintContainerCellKey;
    else if ([representedObject isKindOfClass:[RNListItem class]] || [representedObject isKindOfClass:[RNItem class]]) 
        key = RNPrintListItemCellKey;
    NSCell *dataCell = [[self detailCells] valueForKey:key];
    [dataCell setRepresentedObject:representedObject];
    return dataCell;
}

-(CGFloat)printHeightForItem:(id)item {
    id representedObject = [item representedObject]; // Using bindings to NSTreeController, item is an NSTreeNode
    if ([representedObject isKindOfClass:[RNDetailHeader class]]) 
        return [(RNDetailHeader *)representedObject headerHeight];
    if ([representedObject isKindOfClass:[RNCategory class]])
        return [RNCategory showsChildren] ? listContainerHeight : genericHeight;
    if ([representedObject isKindOfClass:[RNAisle class]])
        return [RNAisle showsChildren] ? listContainerHeight : genericHeight;
    if ([representedObject isKindOfClass:[RNListItem class]] && [(RNListItem *)representedObject notes])
        return itemWithNotesHeight;
    return genericHeight;
}

@end
